#
# LibrarySourceViewItem.py
#
# This work is released under the GNU GP, version 2 or later.
#

from qt import *
from PlaylistSourceViewItem import *
from TrackDrag import *
from PodTrackDrag import *

#
# Master library playlist
#
class LibrarySourceViewItem(PlaylistSourceViewItem):
	def __init__(self,container,source):
		PlaylistSourceViewItem.__init__(self,container,source)
		self.setRenameEnabled(0,False)
		self.wantsTrackDrags = True
		self.canExport = True
		self.setText(0,i18n("Library"))
		self.setDragEnabled(False)
		self.setFont(11,True)

	#
	# Determines the order of the sources
	#
	def makeKey(self):
		return u'E' # appear before the playlists

	def buildPopup(self,mainWindow):
		self.popup = QPopupMenu()
		id = self.popup.insertItem(i18n("Export Song List"),mainWindow.slotExportLibrary)

	def loadPopup(self):
		pass

	def iconFileName(self): return "sourcelibrary.png"

	def select(self,container):
		container.emit(PYSIGNAL("selectLibrary"),(None,None))

	#
	# allow file system drags
	# allow track drags from the trash only
	#
	def acceptDrag(self,event):
		if not self.wantsTrackDrags: return False
		elif self.wantsFileDrags and QUriDrag.canDecode(event): return True
		elif LTrackDrag.canDecode(event):
			drag = LTrackDrag.decode(event)
			playlist = self.library.playlistWithName(drag['Playlist'])
			if playlist==self.trash: return True
		elif PodTrackDrag.canDecode(event):
			return True
		elif RemoteTrackDrag.canDecode(event):
			return True
		return False

	#
	# handle file system drags
	# and track drags if source is the trash
	#
	def dropped(self,event):
		#self.printDragFormats(event)
		if LTrackDrag.canDecode(event):
			drag = LTrackDrag.decode(event)
			#print "library got",drag
			playlist = self.library.playlistWithName(drag['Playlist'])
			trackIDs = drag['TrackIDs']
			if playlist == self.trash:
				self.libraryPlaylist.addTrackIDs(trackIDs)
				self.trash.removeTrackIDs(trackIDs)
		elif PodTrackDrag.canDecode(event):
			from DB.PodLibrary import PodLibrary
			from DB.PodManager import PodManager
			drag = PodTrackDrag.decode(event)
			trackIDs = drag['TrackIDs']
			tracks = PodLibrary.singleton().tracksWithTrackIDs(trackIDs)
			PodManager.singleton().downloadTracksToPlaylist(None,tracks)
		elif RemoteTrackDrag.canDecode(event):
			drag = RemoteTrackDrag.decode(event)
			tracks = []
			for trackplist in drag['Tracks']:
				track = Track()
				track.setPList(trackplist)
				tracks.append(track)
			Services.Downloader.singleton().downloadTracks(tracks,None,self.library)
		elif QUriDrag.canDecode(event):
			uris = QStringList()
			if QUriDrag.decodeLocalFiles(event,uris):
				self.library.importFiles(removeDuplicates(uris),None)

	def doubleClick(self):
		pass
